package com.hzhr.iot.collect.protocol.decipher;

import com.hzhr.iot.collect.constant.UpDownEnum;
import com.hzhr.iot.collect.service.helper.Device_IotDeviceServiceHelper;
import com.hzhr.iot.collect.service.helper.Device_IotDevice_KeyServiceHelper;
import com.hzhr.iot.collect.util.StrUtil;
import com.hzhr.iot.core.exception.ServiceException;
import com.hzhr.iot.device.sdk.model.iotDevice_key.IotDevice_KeyModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class Decipher2 implements Decipher {
    @Autowired
    Device_IotDeviceServiceHelper device_iotDeviceServiceHelper;
    @Autowired
    Device_IotDevice_KeyServiceHelper device_iotDevice_keyServiceHelper;

    @Override
    public String decipher(String message, int protocolId, String deviceId, UpDownEnum upDownFlag) {
        String encryptedByte = null;

        IotDevice_KeyModel iotDevice_keyModel = null;
        try {
            iotDevice_keyModel = device_iotDevice_keyServiceHelper.getByIotDeviceId(deviceId);
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        if (iotDevice_keyModel == null) return message;

        if (UpDownEnum.UP.equals(upDownFlag)) {
            encryptedByte = iotDevice_keyModel.getUpKey();
        } else if (UpDownEnum.DOWN.equals(upDownFlag)) {
            encryptedByte = iotDevice_keyModel.getDownKey();
        }
        if (encryptedByte == null) return message;


        Integer targetByteStartIndex = 8;//目标字节起始位置
        Integer targetByteEndIndex = message.length() - 6;//目标字节结束位置
        String targetByte = StrUtil.substring(message, targetByteStartIndex, targetByteEndIndex);

        //解密
        byte[] targetBs = StrUtil.hexStr2byte(targetByte);
        byte[] encryptedBs = StrUtil.hexStr2byte(encryptedByte);
        byte encryptedB = encryptedBs[0];
        byte[] oriBs = new byte[targetBs.length];
        for (int i = 0; i < targetBs.length; i++) {
            byte targetB = targetBs[i];
            targetB ^= encryptedB;
            oriBs[i] = targetB;
        }
        String oriByte = StrUtil.byte2hexStr(oriBs);//原始字节(解密后的字节)

        StringBuilder oriMessageSb = new StringBuilder(message);
        oriMessageSb.replace(targetByteStartIndex, targetByteEndIndex,
                oriByte);
        message = oriMessageSb.toString();

        return message;
    }
}
